package com.becca.cake.core.qiniu;

import java.io.File;
import java.text.MessageFormat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.becca.cake.core.constant.CommonConstants;
import com.becca.cake.core.qiniu.bean.QiNiuResponse;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

/**
 * 七牛云商品图片储存
 * @copyright  尊星(上海)信息科技有限公司
 * @author hejinguo
 * @date 2016年5月25日 下午11:29:09
 */
public class QiNiuGoodsPicTemplate {
    private static final Logger logger     = LoggerFactory.getLogger(QiNiuGoodsPicTemplate.class);
    private static Auth         auth;
    private static final String URL_FORMAT = "http://{0}/{1}";

    static {
        auth = Auth.create(CommonConstants.QINIU_ACCESSKEY, CommonConstants.QINIU_SECRETKEY);
    }

    /**
     * 获取token
     * @return
     */
    private static String getGoodsUploadToken() {
        return auth.uploadToken(CommonConstants.QINIU_GOODSBUCKETNAME);
    }

    /**
     * 获取File token
     * @return
     */
    private static String getFileUploadToken() {
        return auth.uploadToken(CommonConstants.QINIU_FILESBUCKETNAME);
    }

    public static QiNiuResponse uploadFile(File localFile, String fileName) {
        QiNiuResponse response = null;
        //step1:上传对象创建
        UploadManager uploadManager = new UploadManager();
        //step2:上传文件
        Response res = null;
        try {
            res = uploadManager.put(localFile, fileName, getGoodsUploadToken());
            //step3:获取响应对象
            response = res.jsonToObject(QiNiuResponse.class);
            response.setSuccess(res.isOK() ? true : false);
        } catch (QiniuException e) {
            Response r = e.response;
            logger.error("七牛云存储上传失败，失败原因:" + r.toString(), e);
        }
        return response;
    }

    /**
     * 获取图片访问路径
     * @param key
     * @return
     */
    public static String getDownloadUrl(String key) {
        return MessageFormat.format(URL_FORMAT, CommonConstants.QINIU_PICPATH, key);

    }

    public static QiNiuResponse uploadFileInfo(File localFile, String fileName) {
        QiNiuResponse response = null;
        //step1:上传对象创建
        UploadManager uploadManager = new UploadManager();
        //step2:上传文件
        Response res = null;
        try {
            res = uploadManager.put(localFile, fileName, getFileUploadToken());
            //step3:获取响应对象
            response = res.jsonToObject(QiNiuResponse.class);
            response.setSuccess(res.isOK() ? true : false);
        } catch (QiniuException e) {
            Response r = e.response;
            logger.error("七牛云存储上传失败，失败原因:" + r.toString(), e);
        }
        return response;
    }

    /**
     * 获取File访问路径
     * @param key
     * @return
     */
    public static String getFileDownloadUrl(String key) {
        return MessageFormat.format(URL_FORMAT, CommonConstants.QINIU_FILEPATH, key);

    }
}
